package icedot.library.common.utils;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.BuildConfig;
import android.support.v4.content.FileProvider;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

import icedot.library.common.base.Logger;

import static android.util.TypedValue.COMPLEX_UNIT_DIP;
import static android.util.TypedValue.COMPLEX_UNIT_IN;
import static android.util.TypedValue.COMPLEX_UNIT_MM;
import static android.util.TypedValue.COMPLEX_UNIT_PT;
import static android.util.TypedValue.COMPLEX_UNIT_PX;
import static android.util.TypedValue.COMPLEX_UNIT_SP;

public class CommonFun
{
    private static final int s_exitApp_time = 1000;    // 秒
    private static long _firstClick = 0;

    /**
     * 长提示信息
     *
     * @param context
     * @param msg
     */
    public static void showHintMsg(Context context, String msg)
    {
        if (StringUtils.isNullOrEmpty(msg) || context == null)
        {
            return;
        }

        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }

    /**
     * 提示信息
     *
     * @param context
     * @param msg
     * @param shortTime true:短提示信息  false:长提示信息
     */
    public static void showHintMsg(Context context, String msg, boolean shortTime)
    {
        if (StringUtils.isNullOrEmpty(msg) || context == null)
        {
            return;
        }
        if (shortTime)
        {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        }

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 按两次BACK建退出程序
     *
     * @param context Activity
     * @param content 提示的内容
     *
     * @return
     */
    public static boolean exitApp_doubleBack(Context context, String content)
    {
        long nowClick = Calendar.getInstance().getTimeInMillis();
        if (nowClick - _firstClick > s_exitApp_time)
        {
            _firstClick = nowClick;
            if (content != null)
            {
                CommonFun.showHintMsg(context, content);
            }
            return false;
        }
        else
        {
            return true;
        }
    }

    /**
     * 清理volley的缓存,否则不使用网络而使用的缓存
     */
    public static void clearCacheFile(Context context)
    {
        File file = context.getCacheDir();
        if (file != null && file.exists() && file.isDirectory())
        {
            for (File item : file.listFiles())
            {
                if (item.isDirectory())
                {
                    for (File sitem : item.listFiles())
                    {
                        sitem.delete();
                    }
                }
                item.delete();
            }
        }
    }

    /**
     * 安装APK
     *
     * @param context
     * @param name
     */
    public static void installApkFromLocal(Context context, String name)
    {
        Intent intent2 = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= 24) {
            intent2.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", new File(name));
            intent2.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent2.setDataAndType(Uri.parse("file://" + name), "application/vnd.android.package-archive");
        }
        context.startActivity(intent2);
    }

    /**
     * 描述：手机号格式验证.
     *
     * @param str 指定的手机号码字符串
     *
     * @return 是否为手机号码格式:是为true，否则false
     */
    public static Boolean isMobileNo(String str)
    {
        String[] phoneHead = {"13", "15", "18"};
        if (str.length() == 11)
        {
            String head = str.substring(0, 2);
            for (String item : phoneHead)
            {
                if (head.equals(item))
                    return true;
            }
        }
        return false;
    }

    //从assets 文件夹中获取文件并读取数据
    public static String getStringFromAssets(Context context, String fileName)
    {
        String result = "";
        try
        {
            InputStream in = context.getResources().getAssets().open(fileName);
            //获取文件的字节数
            int length = in.available();
            //创建byte数组
            byte[] buffer = new byte[length];
            //将文件中的数据读到byte数组中
            in.read(buffer);
            result = new String(buffer, "UTF-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    // START----------------------------------JOSN---------------------------------
    public static void getObjectFromJson(Object obj, JSONObject json) throws Exception
    {
        Field[] fieldList = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fieldList.length; i++)
        {
            Field field = fieldList[i];
            String name = field.getName();
            if (json.isNull(name.substring(1)))
            {
                continue;
            }
            Type type = field.getType();
            if (type.toString().equals("class java.lang.String"))
            {
                field.set(obj, json.getString(name.substring(1)));
            }
            else if (type.toString().equals("int"))
            {
                field.set(obj, json.getInt(name.substring(1)));
            }
            else if (type.toString().equals("long"))
            {
                field.set(obj, json.getLong(name.substring(1)));
            }
            else if (type.toString().equals("float") || type.toString().equals("double"))
            {
                field.set(obj, json.getDouble(name.substring(1)));
            }
            else
            {
                Logger.showDebugMsg(Logger.s_error, "Exception", type.toString() + " not process");
            }
        }
    }

    public static JSONObject getJsonFromObject(Object obj, JSONObject json) throws Exception
    {
        if (json == null)
        {
            json = new JSONObject();
        }
        Field[] fieldList = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fieldList.length; i++)
        {
            Field field = fieldList[i];
            String name = field.getName();
            json.put(name.substring(1), field.get(obj));
        }
        return json;
    }

    public static boolean getBoolean(JSONObject json, String key) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }

        if (json.isNull(key))
        {
            return false;
        }
        return json.getBoolean(key);
    }

    public static boolean getBoolean(JSONObject json, String key, boolean defultVal) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }

        if (!json.has(key) || json.isNull(key))
        {
            return defultVal;
        }
        return json.getBoolean(key);
    }

    public static String getString(JSONObject json, String key) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }
        if (json.isNull(key))
        {
            return "";
        }
        return json.getString(key);
    }

    public static String getString(JSONObject json, String key, String defaultVal) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
            return defaultVal;
        }

        if (!json.has(key) || json.isNull(key))
        {
            return defaultVal;
        }
        if (StringUtils.isNullOrEmpty(json.getString(key)))
        {
            return defaultVal;
        }
        return json.getString(key);
    }

    public static int getInt(JSONObject json, String key) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }

        if (json.isNull(key))
        {
            return 0;
        }
        return json.getInt(key);
    }

    public static int getInt(JSONObject json, String key, int defaultVal) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }
        if (!json.has(key) || json.isNull(key))
        {
            return defaultVal;
        }
        return json.getInt(key);
    }

    public static long getLong(JSONObject json, String key) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }
        if (json.isNull(key))
        {
            return 0;
        }
        return json.getLong(key);
    }

    public static long getLong(JSONObject json, String key, long defaultVal) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }
        if (!json.has(key) || json.isNull(key))
        {
            return defaultVal;
        }
        return json.getLong(key);
    }

    public static double getDouble(JSONObject json, String key) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }
        if (json.isNull(key))
        {
            return 0.0;
        }
        return json.getDouble(key);
    }

    public static double getDouble(JSONObject json, String key, double defaultVal) throws JSONException
    {
        if (!json.has(key))
        {
            Logger.errorMsg(" " + key + " not find");
        }
        if (!json.has(key) || json.isNull(key))
        {
            return defaultVal;
        }
        return json.getDouble(key);
    }

    // END----------------------------------JOSN---------------------------------
}
